package org.example.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author : wer
 * @Date: 2025/7/7 15:29
 * @Description: 响应时间全局过滤器
 */

@Slf4j
@Component
public class RtGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        long startTime = System.currentTimeMillis();
        log.info("请求 {} 开始！时间：{}", request.getURI().getPath(), startTime);

        // 请求放行
        Mono<Void> filter = chain.filter(exchange).doFinally(res -> {
            long endTime = System.currentTimeMillis();
            log.info("请求结束！时间：{}，共耗时：{}", endTime, endTime - startTime);
        });


        return filter;
    }
}
